package ui

import (
	"strings"
	"path/filepath"
	"kumachan/standalone/qt"
	"kumachan/stdlib"
)


type WebAsset interface {
	Underlying() *stdlib.Asset
	InjectTo(view qt.CustomWebView)
}
func WebAssetFrom(asset *stdlib.Asset) WebAsset {
	switch asset.MIME {
	case "font/ttf":
		var path = asset.Path
		var name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
		var family = name
		var weight = "normal"
		var style = "normal"
		if strings.HasSuffix(name, "-Regular") {
			family = strings.TrimSuffix(name, "-Regular")
		} else if strings.HasSuffix(name, "-Bold") {
			family = strings.TrimSuffix(name, "-Bold")
			weight = "bold"
		} else if strings.HasSuffix(name, "-Italic") {
			family = strings.TrimSuffix(name, "-Italic")
			style = "italic"
		} else if strings.HasSuffix(name, "-BoldItalic") {
			family = strings.TrimSuffix(name, "-BoldItalic")
			weight = "bold"
			style = "italic"
		}
		return WebAssetTTF {
			Asset:  asset,
			FontId: FontId {
				Family: family,
				Weight: weight,
				Style:  style,
			},
		}
	case "text/css":
		return WebAssetCSS {
			Asset: asset,
		}
	default:
		return WebAssetPlain {
			Asset: asset,
		}
	}
}
func registerAssets(view qt.CustomWebView, assets ([] WebAsset)) {
	for _, item := range assets {
		var underlying = item.Underlying()
		var key_q, key_del = qt.NewString(underlying.Key())
		var mime_q, mime_del = qt.NewString(underlying.MIME)
		view.RegisterAsset(key_q, mime_q, underlying.Data)
		mime_del()
		key_del()
	}
}
func injectAssets(view qt.CustomWebView, assets ([] WebAsset)) {
	for _, item := range assets {
		item.InjectTo(view)
	}
}

type WebAssetPlain struct {
	Asset  *stdlib.Asset
}
func (plain WebAssetPlain) Underlying() *stdlib.Asset {
	return plain.Asset
}
func (plain WebAssetPlain) InjectTo(_ qt.CustomWebView) {
	return
}

type WebAssetCSS struct {
	Asset  *stdlib.Asset
}
func (css WebAssetCSS) Underlying() *stdlib.Asset {
	return css.Asset
}
func (css WebAssetCSS) InjectTo(view qt.CustomWebView) {
	var key = css.Asset.Key()
	var key_q, del = qt.NewString(key)
	defer del()
	view.InjectCSS(key_q)
}

type WebAssetJS struct {
	Asset  *stdlib.Asset
}
func (js WebAssetJS) Underlying() *stdlib.Asset {
	return js.Asset
}
func (js WebAssetJS) InjectTo(view qt.CustomWebView) {
	var key = js.Asset.Key()
	var key_q, del = qt.NewString(key)
	defer del()
	view.InjectJS(key_q)
}

type WebAssetTTF struct {
	Asset   *stdlib.Asset
	FontId  FontId
}
type FontId struct {
	Family  string
	Weight  string
	Style   string
}
func (ttf WebAssetTTF) Underlying() *stdlib.Asset {
	return ttf.Asset
}
func (ttf WebAssetTTF) InjectTo(view qt.CustomWebView) {
	var key_q, del1 = qt.NewString(ttf.Asset.Key()); defer del1()
	var family_q, del2 = qt.NewString(ttf.FontId.Family); defer del2()
	var weight_q, del3  = qt.NewString(ttf.FontId.Weight); defer del3()
	var style_q, del4 = qt.NewString(ttf.FontId.Style); defer del4()
	view.InjectTTF(key_q, family_q, weight_q, style_q)
}


